/*!
 @header ProductFormViewController.m
 @author 王 文彬
 @version 1.0.0 2013/02/01 Creation
 Copyright (c) 2013年 mypocketbaby. All rights reserved.
 */


#import "ProductFormViewController.h"
#import "Config.h"
#import "Helper.h"
#import "CirclePickerViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "JMFBase.h"
#import "ProductAdvViewController.h"
#import "AddressPickerViewController.h"


//  -----------------------类详细介绍-----------------------
//
//  <业务描述>：此类是可重用的，VC加载后，会调用resetView方法，此方法会初始化view的显示内容以及外观，其中会判断从ProductListVC中传递过来的
//           product对象是否为nil，如果不为nil，那么表示此时用户在修改或者预览商品信息，此时就会向服务器请求此商品的详情信息，并渲染在此viewcontroller的view上，
//           此时textfield无边框；否则用户就是在添加商品，就简单初始化此viewcontroller的view，让用户填写商品信息，此时textfield有边框。
//
//
//  <功能描述>：用户添加图片时，允许用户在添加的同时，删除以前的。
//  	<实现描述>：当用户点击未选择过图片的背景按钮时，弹出来的actionsheet是没有删除图片按钮的；否则有删除图片按钮
//
//               此处以添加商品举例，修改商品的其它操作查看注意事项。
//               删除操作时，会得到用户点击的按钮的tag，据此来判断用户是要删除哪一张图片.
//
//               1、如果删除第三张，那么就将第三张图片的位置显示默认的背景，提示用户图片已删除。
//               2、如果删除第二张，那么就要判断用户是否上传过第三张，如上传过，那么将第三张图片移至第二张图片的位置，并将
//               第三张图片的位置显示默认的背景，提示用户图片已删除，并且更新request的param；如未上传过，那么将第二张图片的
//               位置显示默认的背景，并隐藏第三张图片的位置的按钮。
//               3、如果删除第一张，那么就要分别判断第二张和第三张同时存在的情况、只存在第二张的情况以及第二张和第三张都没有的情况。
//                 1) 第二张和第三张同时存在的情况，那么将此两张图片的位置依次往前面移动一个位置，将原第三张图片的位置设为默认的背景，表示此处可添加图片。
//                 2) 只存在第二张的情况，那么将第二张图片移到原第一张图片的位置，将原第二张图片的位置设为默认的背景，隐藏第三张图片的位置。
//                 3) 第二张和第三张都没有的情况，那么将原第一张图片的位置设为默认的背景，隐藏第二张图片的位置。
//
//      <注意事项>：如果是在修改商品信息，那么在删除图片时，每次删除记录下被删除的图片的id，以便向服务器请求修改。
//
//   <业务描述>：交货方式由原来的配送方式演变而来，分为“卖家快递上门”和“买家上门自取”。商品同时支持快递和自取，当用户选择了快递时，
//              在此view下方会弹出物流运费选项，“卖家承担运费”和“买家承担运费”，单选，当点击“买家承担运费”时，在view下方会弹出
//              发货城市、同城运费以及全国运费的输入框。
//              用户点击自取时，下方显示取货地址view，供用户点击选择取货地址。
//
//  -----------------------类升级日志-----------------------
//
//  修改人   修改时间        修改描述                              版本
//
//  周益     2013-6-5      修改交货方式；添加对简单物流的支持         1.0.1
//  Ben     2013-6-19     增加了推广功能                          1.6.4
/*!
 @enum
 @abstract 配送方式类型
 @constant expressType 49
 @constant takeType 50
 */
typedef enum{
    
    expressType = 49,
    takeType
    
}DeliveryWayType;


@interface ProductFormViewController ()
{
    UILabel *_promptLabelInAddressView;
    UILabel *_promptLabelInFreightView;
}

@end

@implementation ProductFormViewController

@synthesize product = _product;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //背景
    self.view.backgroundColor = _SYS_COLOR_BACKGROUND;
    
    //导航栏左按钮：返回
    UIButton* backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    //导航按钮右按钮：确定
    UIButton* saveButton = [Helper buttonWithStyle:ButtonStyleNavigationDone];
    [saveButton addTarget:self action:@selector(saveButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:saveButton];
    

    _scrollView = [[CustomScrollView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, _SYS_FRAME_HEIGHT)];
    _scrollView.backgroundColor = _SYS_COLOR_BACKGROUND;
    _scrollView.customDelegate = self;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.showsHorizontalScrollIndicator = NO;
    [_scrollView setContentSize:CGSizeMake(self.view.frame.size.width, self.view.frame.size.height + 300.0f)];
    [self.view addSubview:_scrollView];
    
    //商品名称
    UIView* nameView = [[UIView alloc] initWithFrame:CGRectMake(10, 5, 300, 40)];
    nameView.backgroundColor = [UIColor whiteColor];
    nameView.layer.cornerRadius = 3;
    nameView.layer.borderWidth = 1;
    nameView.layer.borderColor = [_SYS_COLOR_003 CGColor];

    //商品名称Label
    UILabel* nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 60, 20)];
    nameLabel.text = _L(@"title_name_03");     //商品名称
    nameLabel.font = _SYS_FONT_003;

    [nameView addSubview:nameLabel];

    //商品名称输入框
    _nameField = [[UITextField alloc] initWithFrame:CGRectMake(80, 8, 200, 24)];
    _nameField.returnKeyType = UIReturnKeyDone;
    _nameField.tag = 88;
    _nameField.delegate = (id)self;
    _nameField.font =_SYS_FONT_006;
    [nameView addSubview:_nameField];

    [_scrollView addSubview:nameView];
    

    //商品介绍
    UIView* descView = [[UIView alloc] initWithFrame:CGRectMake(10, nameView.frame.origin.y + nameView.frame.size.height + 5.0f, 300, 70)];
    descView.backgroundColor = [UIColor whiteColor];
    descView.layer.cornerRadius = 3;
    descView.layer.borderWidth = 1;
    descView.layer.borderColor = [_SYS_COLOR_003 CGColor];
    
    //商品介绍Label
    UILabel* descLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 25, 60, 20)];
    descLabel.text = _L(@"title_desc_01");         //商品介绍
    descLabel.font = _SYS_FONT_003;
    
    [descView addSubview:descLabel];
    
    //商品介绍输入框
    _descTextView = [[UITextView alloc] initWithFrame:CGRectMake(80, 5, 200, 60)];
    _descTextView.returnKeyType = UIReturnKeyDone;
    _descTextView.layer.cornerRadius = 3;
    _descTextView.layer.borderColor = [[UIColor whiteColor] CGColor];
    _descTextView.layer.borderWidth = 1.0f;
    _descTextView.font = _SYS_FONT_003;
    _descTextView.delegate = (id)self;
    
    [descView addSubview:_descTextView];
    
    [_scrollView addSubview:descView];
    
    //商品产地
    UIView *originView = [[UIView alloc] initWithFrame:CGRectMake(10.0f, descView.frame.origin.y + descView.frame.size.height + 5.0f, 300.0f, 40.0f)];
    originView.backgroundColor = [UIColor whiteColor];
    originView.layer.cornerRadius = 3;
    originView.layer.borderWidth = 1;
    originView.layer.borderColor = [_SYS_COLOR_003 CGColor];

    //商品产地Label
    UILabel* originLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 60, 20)];
    originLabel.text = _L(@"title_origin_01");         //商品介绍
    originLabel.font = _SYS_FONT_003;
    
    [originView addSubview:originLabel];
    
    _originField = [[UITextField alloc] initWithFrame:CGRectMake(80, 8, 200, 24)];
    _originField.returnKeyType = UIReturnKeyDone;
    _originField.tag = 89;
    _originField.delegate = (id)self;
    _originField.font =_SYS_FONT_006;
    [originView addSubview:_originField];
    
    [_scrollView addSubview:originView];
    
    //商品图片
    UIView* imageView = [[UIView alloc] initWithFrame:CGRectMake(10, originView.frame.origin.y + originView.frame.size.height + 5.0f, 300, 75)];
    imageView.backgroundColor = _SYS_COLOR_004;
    imageView.layer.cornerRadius = 3;
    imageView.layer.borderWidth = 1;
    imageView.layer.borderColor = [_SYS_COLOR_003 CGColor];
    
    //商品图片Label
    UILabel* imageLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 27, 60, 20)];
    imageLabel.text = _L(@"title_image_01");           //商品图片
    imageLabel.backgroundColor = [UIColor clearColor];
    imageLabel.font = _SYS_FONT_003;
    
    [imageView addSubview:imageLabel];
    
    //图片1
    _imageButton1 = [[UIButton alloc] initWithFrame:CGRectMake(80, 5, 65, 65)];
    _imageButton1.tag = 1;
    [_imageButton1 setImage:[UIImage imageNamed:@"transaction_btn_001"] forState:UIControlStateNormal];
    [_imageButton1 addTarget:self action:@selector(imageButtonEvent:) forControlEvents:UIControlEventTouchUpInside];

    //图片2
    _imageButton2 = [[UIButton alloc] initWithFrame:CGRectMake(150, 5, 65, 65)];
    _imageButton2.tag = 2;
    [_imageButton2 setImage:[UIImage imageNamed:@"transaction_btn_001"] forState:UIControlStateNormal];
    [_imageButton2 addTarget:self action:@selector(imageButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    
    //图片3
    _imageButton3 = [[UIButton alloc] initWithFrame:CGRectMake(220, 5, 65, 65)];
    _imageButton3.tag = 3;
    [_imageButton3 setImage:[UIImage imageNamed:@"transaction_btn_001"] forState:UIControlStateNormal];
    [_imageButton3 addTarget:self action:@selector(imageButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    
    [imageView addSubview:_imageButton1];
    [imageView addSubview:_imageButton2];
    [imageView addSubview:_imageButton3];
    
    [_scrollView addSubview:imageView];
    
    
    //商品价格
    UIView* priceView = [[UIView alloc] initWithFrame:CGRectMake(10, imageView.frame.origin.y + imageView.frame.size.height + 5.0f, 300, 45)];
    priceView.backgroundColor = [UIColor whiteColor];
    priceView.layer.cornerRadius = 3;
    priceView.layer.borderWidth = 1;
    priceView.layer.borderColor = [_SYS_COLOR_003 CGColor];
    
    //商品价格Label
    UILabel* priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 70, 20)];
    priceLabel.text = _L(@"title_price_01");     //商品价格
    priceLabel.backgroundColor = [UIColor clearColor];
    priceLabel.font = _SYS_FONT_003;
    
    [priceView addSubview:priceLabel];
    
    //产品价格输入框
    _priceField = [[UITextField alloc] initWithFrame:CGRectMake(80, 9, 100, 24)];
    _priceField.returnKeyType = UIReturnKeyDone;
    _priceField.keyboardType = UIKeyboardTypeDecimalPad;
    _priceField.tag = 100;
    _priceField.delegate = self;
    [priceView addSubview:_priceField];
    
    //单位label
    _unitLabel = [[UILabel alloc] initWithFrame:CGRectMake(_priceField.frame.origin.x + _priceField.frame.size.width + 2.0f, 10, 65, 20)];
    _unitLabel.font = _SYS_FONT_004;
    _unitLabel.textColor = _SYS_COLOR_003;
    [priceView addSubview:_unitLabel];
    
    //单位按钮
    UIButton* unitButton = [[UIButton alloc] initWithFrame:CGRectMake(_unitLabel.frame.size.width + _unitLabel.frame.origin.x + 5.0f, 10, 34.5f, 22.5f)];
    [unitButton setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_btn_004@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [unitButton addTarget:self action:@selector(unitButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    [priceView addSubview:unitButton];
    
    [_scrollView addSubview:priceView];
    
    //商品数量
    UIView* numView = [[UIView alloc] initWithFrame:CGRectMake(10, priceView.frame.origin.y + priceView.frame.size.height + 5.0f, 300, 40)];
    numView.backgroundColor = [UIColor whiteColor];
    numView.layer.cornerRadius = 3;
    numView.layer.borderWidth = 1;
    numView.layer.borderColor = [_SYS_COLOR_003 CGColor];
    
    //商品名称Label
    UILabel* numLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 60, 20)];
    numLabel.text = _L(@"title_num_01");     //商品数量
    numLabel.font = _SYS_FONT_003;
    
    [numView addSubview:numLabel];
    
    //商品数量输入框
    _numField = [[UITextField alloc] initWithFrame:CGRectMake(80, 9, 200, 24)];
    _numField.returnKeyType = UIReturnKeyDone;
    _numField.tag = 86;
    _numField.keyboardType = UIKeyboardTypeDecimalPad;
    _numField.delegate = (id)self;
    [numView addSubview:_numField];
    
    [_scrollView addSubview:numView];
    
    
    //销售区域
    _areaView = [[UIView alloc] initWithFrame:CGRectMake(10, numView.frame.origin.y + numView.frame.size.height + 5.0f, 300, 40)];
    _areaView.backgroundColor = [UIColor whiteColor];
    _areaView.layer.cornerRadius = 3;
    _areaView.layer.borderWidth = 1;
    _areaView.layer.borderColor = [_SYS_COLOR_003 CGColor];

    //销售区域label
    UILabel* areaLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 70, 20)];
    areaLabel.text = _L(@"title_area_01");    //销售区域
    areaLabel.backgroundColor = [UIColor clearColor];
    areaLabel.font = _SYS_FONT_003;
    
    [_areaView addSubview:areaLabel];
    
    //销售区域输入框
    _areaField = [[UITextField alloc] initWithFrame:CGRectMake(80, 8, 200, 24)];
    _areaField.tag = 99;
    _areaField.font = _SYS_FONT_006;
    _areaField.delegate = (id)self;
    [_areaView addSubview:_areaField];
    
    
    [_scrollView addSubview:_areaView];

    //交货方式，如果是自取，那么交货方式下面存在收货地址；
    //如果是快递，那么则是物流运费 和发货城市 并且要设置运费
    _deliveryWayView = [[UIView alloc] initWithFrame:CGRectMake(10, _areaView.frame.size.height + _areaView.frame.origin.y + 5.0f, 300, 75)];
    
    _deliveryWayView.backgroundColor = [UIColor whiteColor];
    _deliveryWayView.layer.cornerRadius = 3;
    _deliveryWayView.layer.borderWidth = 1;
    _deliveryWayView.layer.borderColor = [_SYS_COLOR_003 CGColor];
    
    [_scrollView addSubview:_deliveryWayView];
    
    //交货方式label
    UILabel* deliveryWayLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 25, 70, 20)];
    deliveryWayLabel.text = _L(@"title_method_01");
    deliveryWayLabel.backgroundColor = [UIColor clearColor];
    deliveryWayLabel.font = _SYS_FONT_003;
    
    [_deliveryWayView addSubview:deliveryWayLabel];
    
    //快递标记按钮
    _expressButton = [[UIButton alloc] initWithFrame:CGRectMake(deliveryWayLabel.frame.origin.x + deliveryWayLabel.frame.size.width + 5.0f, 0.0f, 110.0f, 30.0f)];
    _expressButton.tag = expressType;
    [_expressButton setSelected:YES];
    [_expressButton addTarget:self action:@selector(switchDeliveryWayButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    [_deliveryWayView addSubview:_expressButton];
    
    
    //快递标记
    _expressImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 15.0f, 14.0f, 14.0f)];
    _expressImageView.image = [UIImage imageNamed:@"com_icon_011"];
    
    [_expressButton addSubview:_expressImageView];
    
    //快递label
    UILabel *expressLabel = [[UILabel alloc] initWithFrame:CGRectMake(_expressImageView.frame.origin.x
                                                                      + _expressImageView.frame.size.width + 5.0f, 10.0f, 90.0f, 20.0f)];
    expressLabel.text = _L(@"title_method_03");   //快递
    expressLabel.font = _SYS_FONT_003;
    expressLabel.textColor = _SYS_COLOR_003;
    
    [_expressButton addSubview:expressLabel];
    
    //自取标记按钮
    _takeButton = [[UIButton alloc] initWithFrame:CGRectMake(deliveryWayLabel.frame.origin.x + deliveryWayLabel.frame.size.width + 5.0f, _expressButton.frame.origin.y + _expressButton.frame.size.height + 5.0f, 110.0f, 30.0f)];
    _takeButton.tag = takeType;
    [_takeButton addTarget:self action:@selector(switchDeliveryWayButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    
    [_deliveryWayView addSubview:_takeButton];
    
    //自取标记
    _takeImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 15.0f, 14.0f, 14.0f)];
    _takeImageView.image = [UIImage imageNamed:@"com_icon_010"];
    
    [_takeButton addSubview:_takeImageView];
    
    //自取label
    UILabel *takeLabel = [[UILabel alloc] initWithFrame:CGRectMake(_takeImageView.frame.origin.x
                                                                      + _takeImageView.frame.size.width + 5.0f, 10.0f, 90.0f, 20.0f)];
    takeLabel.text = _L(@"title_method_02");   //自取
    takeLabel.font = _SYS_FONT_003;
    takeLabel.textColor = _SYS_COLOR_003;
    
    [_takeButton addSubview:takeLabel];
    
    
    //line
    _lineImageView_1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, _takeButton.frame.size.height + _takeButton.frame.origin.y + 10.0f, 300, 1.0f)];
    _lineImageView_1.backgroundColor = [UIColor colorWithRed:224/255.0f green:224/255.0f blue:224/255.0f alpha:1.0f];
    [_deliveryWayView addSubview:_lineImageView_1];
    _lineImageView_1.alpha = 0.0f;
    //物流运费 （此部分在自取下的高度为0）
    
    _fareLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, _lineImageView_1.frame.origin.y + _lineImageView_1.frame.size.height + 25.0f, 70, 20)];
    _fareLabel.backgroundColor = [UIColor clearColor];
    _fareLabel.font = _SYS_FONT_003;
    _fareLabel.text = _L(@"title_fare_01");
    _fareLabel.alpha = 0.0f;
    [_deliveryWayView addSubview:_fareLabel];

    
    //圈子部分的子视图
    _circleView = [[UIView alloc] initWithFrame:CGRectMake(10, _freightView.frame.origin.y
                                                                  + _freightView.frame.size.height + 5.0f, 300, 75)];
    _circleView.backgroundColor = [UIColor whiteColor];
    _circleView.layer.cornerRadius = 3;
    _circleView.layer.borderWidth = 1;
    _circleView.layer.borderColor = [_SYS_COLOR_003 CGColor];
    [_scrollView addSubview:_circleView];
    
    //圈子提示信息label
    _circleTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 115, 20)];
    _circleTitleLabel.font = _SYS_FONT_003;
    [_circleView addSubview:_circleTitleLabel];
    
    //选中的圈子的label
    _circleLabel = [[UILabel alloc] initWithFrame:CGRectMake(125, 12, 175, 15)];
    _circleLabel.font = _SYS_FONT_001;
    _circleLabel.textColor = _SYS_COLOR_006;
    [_circleView addSubview:_circleLabel];
    
    //画分割线
    UIImageView* line2 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 35, 300, 1)];
    line2.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_bg_008@2x" ofType:@"png"]];
    [_circleView addSubview:line2];
    
    //选择要发布的圈子的按钮
    _circleButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 42, 120, 25)];
    _circleButton.titleLabel.font = _SYS_FONT_001;
    [_circleButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_btn_007_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [_circleButton addTarget:self action:@selector(circleButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    [_circleView addSubview:_circleButton];
    

    //广告子视图
    _advView = [[UIView alloc] initWithFrame:CGRectMake(10, _circleView.frame.origin.y + _circleView.frame.size.height + 5.0f, 300, 75)];
    _advView.backgroundColor = [UIColor whiteColor];
    _advView.layer.cornerRadius = 3;
    _advView.layer.borderWidth = 1;
    _advView.layer.borderColor = [_SYS_COLOR_003 CGColor];
    [_scrollView addSubview:_advView];
    
    //广告文字Text
    UITextView* advTitle = [[UITextView alloc] initWithFrame:CGRectMake(3, 0, 290, 40)];
    advTitle.font = _SYS_FONT_003;
    advTitle.text = _L(@"title_72");
    advTitle.scrollEnabled = false;
    [_advView addSubview:advTitle];
    
    //广告按钮
    UIButton* advButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 45, 120, 25)];
    [advButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_btn_018_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [advButton setTitle:_L(@"btn_yes_22") forState:UIControlStateNormal];
    advButton.titleLabel.font = _SYS_FONT_001;
    [advButton addTarget:self action:@selector(advButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    [_advView addSubview:advButton];

    
    //按钮组视图
    _buttonsView = [[UIView alloc] initWithFrame:CGRectMake(0, _SYS_FRAME_HEIGHT - 44 - 40, _SYS_FRAME_WIDTH, 40)];
    _buttonsView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_bg_005@2x" ofType:@"png"]]];
    
    //停止销售按钮
    _stopSellingButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 7, 70, 30)];
    _stopSellingButton.titleLabel.font = _SYS_FONT_003;
    _stopSellingButton.hidden = true;
    [_stopSellingButton setTitle:_L(@"btn_sell_01") forState:UIControlStateNormal];   //停止销售
    [_stopSellingButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_btn_002_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [_stopSellingButton addTarget:self action:@selector(stopSellingButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    [_buttonsView addSubview:_stopSellingButton];
    
    //恢复销售按钮
    _sellingButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 7, 70, 30)];
    _sellingButton.titleLabel.font = _SYS_FONT_003;
    _sellingButton.hidden = true;
    [_sellingButton setTitle:_L(@"btn_sell_02") forState:UIControlStateNormal];    //恢复销售
    [_sellingButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_btn_002_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [_sellingButton addTarget:self action:@selector(sellingButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    [_buttonsView addSubview:_sellingButton];
    
    //删除按钮
    UIButton* removeButton = [[UIButton alloc] initWithFrame:CGRectMake(_SYS_FRAME_WIDTH - 10 - 70, 7, 70, 30)];
    removeButton.titleLabel.font = _SYS_FONT_003;
    [removeButton setTitle:_L(@"btn_delete_02") forState:UIControlStateNormal];    //删除商品
    [removeButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_btn_003_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [removeButton addTarget:self action:@selector(removeButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    [_buttonsView addSubview:removeButton];
    
    [self.view addSubview:_buttonsView];
    
    
    //此处如果单位数据源为空的话，就要重新向服务器请求一次
    //主要用于VC重用
    if (_unitDataSource == nil) {
        
        JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_PRODUCT_UNIT_LIST];
        NSDictionary* dict = [request synchronous];
        
        JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
        if (jmf.status == JMStatusSucceed) {
            _unitDataSource = [[NSMutableArray alloc] init];
            
            NSArray* items = [dict valueForKey:@"data"];
            for (int i = 0; i < items.count; i++) {
                [_unitDataSource addObject:[items objectAtIndex:i]];
            }
        }
        else {
            [Helper easyShowJMFStatus:jmf];
        }
    }
    
    //刷新视图
    [self resetView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated
{
    if (iOS7) {
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    }
}


#pragma mark - 私有方法

/*!
 @abstract 商品setter方法
 */
- (void)setProduct:(NSDictionary *)product
{
    _product = product;
    _address = _product[@"consignee"];
    [self resetView];
}

/*!
 @abstract 刷新视图
 为保证正确重用，在VC显示加载后，视图上的显示内容会被reset。同时判断_product是否nil，如果不为nil，那么用户的行为是查看商品详情，将所有的textfield设置成
 无边框，然后渲染商品信息；如果_product不为nil，那么用户的行为是添加新商品，将所有的textfield设置成有边框。
 */
- (void)resetView
{
    //重置按钮检测变量为假，默认是保存按钮被点击
    _advButtonOnClick = false;
    
    _scrollView.contentOffset = CGPointMake(0.0f, 0.0f);
    [_scrollView setContentSize:CGSizeMake(self.view.frame.size.width, self.view.frame.size.height + 300.0f)];
    [_nameField resignFirstResponder];
    [_descTextView resignFirstResponder];
    [_originField resignFirstResponder];
    [_priceField resignFirstResponder];
    [_numField resignFirstResponder];
    [_deliveryCityTextField resignFirstResponder];
    [_localFareTextField resignFirstResponder];
    [_nationwideFareTextField resignFirstResponder];
    [_unitPickerView removeFromSuperview];
    [_customPickerView removeFromSuperview];
    
    _nameField.text = @"";
    _descTextView.text = @"";
    _originField.text = @"";
    _priceField.text = @"1";
    _areaField.text = @"";
    _unitLabel.text = @"元/斤";
    _numField.text = @"";
    _circleLabel.text = @"";
    _deliveryCityTextField.text = @"";
    _localFareTextField.text = @"";
    _nationwideFareTextField.text = @"";
    
    _image1 = nil;
    _image2 = nil;
    _image3 = nil;
    
    _consIdSelected = [NSNumber numberWithInt:0];
    _currentImageButton = nil;
    _buttonsView.hidden = true;
    _sellingButton.hidden = true;
    _stopSellingButton.hidden = true;
    
    [_imageButton1 setImage:[UIImage imageNamed:@"transaction_btn_001"] forState:UIControlStateNormal];
    [_imageButton2 setImage:[UIImage imageNamed:@"transaction_btn_001"] forState:UIControlStateNormal];
    [_imageButton3 setImage:[UIImage imageNamed:@"transaction_btn_001"] forState:UIControlStateNormal];
    _currentImageButton = nil;
    _imageButton2.hidden = true;
    _imageButton3.hidden = true;
    
    _imageId1 = 0;
    _imageId2 = 0;
    _imageId3 = 0;
    
    _imageDelIds = [[NSMutableArray alloc] init];
    _imageUpload = [[NSMutableArray alloc] init];
    
    _expressImageView.image = [UIImage imageNamed:@"com_icon_010"];
    _takeImageView.image = [UIImage imageNamed:@"com_icon_010"];
    _takeButton.selected = false;
    _expressButton.selected = false;
    
    [self sellerPayFare:YES];
    
    [self setAlphaFareForWhoView:0.0f];
    [self setAlphaFareView:0.0f];
    [self hideAddressView];
    
    if (_product != nil) {

        [_scrollView setContentSize:CGSizeMake(self.view.frame.size.width, self.view.frame.size.height + 390.0f)];
        self.title = _L(@"vc_title_020");    //商品详情
        _descTextView.layer.borderColor = [[UIColor whiteColor] CGColor];
        _originField.borderStyle = UITextBorderStyleNone;
        _nameField.borderStyle = UITextBorderStyleNone;
        _priceField.borderStyle = UITextBorderStyleNone;
        _areaField.borderStyle = UITextBorderStyleNone;
        _numField.borderStyle = UITextBorderStyleNone;
        _deliveryCityTextField.borderStyle = UITextBorderStyleNone;
        _localFareTextField.borderStyle = UITextBorderStyleNone;
        _nationwideFareTextField.borderStyle = UITextBorderStyleNone;
        
        _buttonsView.hidden = false;
        _circleTitleLabel.text = _L(@"title_circle_01");    //已经发布的圈子：
        [_circleButton setTitle:_L(@"btn_circle_01") forState:UIControlStateNormal];   //再次发布商品商讯
        
        NSArray* pictures = [_product objectForKey:@"pictures"];

        for (int i = 0; i < pictures.count; i++) {
            if (i == 0) {
                _imageId1 = [[[pictures objectAtIndex:i] objectForKey:@"id"] intValue];
                _imageButton2.hidden = false;
            }
            else if (i == 1) {
                _imageId2 = [[[pictures objectAtIndex:i] objectForKey:@"id"] intValue];
                _imageButton3.hidden = false;
            }
            else {
                _imageId3 = [[[pictures objectAtIndex:i] objectForKey:@"id"] intValue];
            }
        }
        
        //交互方式
        int deliveryMode = [[_product objectForKey:@"deliveryMode"] intValue];
        
        //买家上门自取
        if (deliveryMode == 0) {
            _takeImageView.image = [UIImage imageNamed:@"com_icon_011"];
            _expressImageView.image = [UIImage imageNamed:@"com_icon_010"];
            
            _takeButton.selected = true;
            _expressButton.selected = false;
        }
        
        //卖家快递上门
        else if (deliveryMode == 1) {
            _takeImageView.image = [UIImage imageNamed:@"com_icon_010"];
            _expressImageView.image = [UIImage imageNamed:@"com_icon_011"];
            
            _takeButton.selected = false;
            _expressButton.selected = true;
        }
        
        
        //快递 自取都支持
        else {
            _takeImageView.image = [UIImage imageNamed:@"com_icon_011"];
            _expressImageView.image = [UIImage imageNamed:@"com_icon_011"];
            
            _takeButton.selected = true;
            _expressButton.selected = true;
            
        }

        [self setAddressViewHidden];
        [self setFreightViewHidden];
        
        JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_PRODUCT_DETAILINFO];
        request.hudOn = true;
        request.hudTitle = _L(@"title_loading_01");
        request.delegate = self;
        [request setSuccessSelector:@selector(getProductInfoSelector:)];
        [request setValue:[_product valueForKey:@"id"] forParameter:@"productId"];
        [request asynchronous];
    }
    else {
        self.title = _L(@"vc_title_021");    //添加商品
        [_circleButton setTitle:_L(@"btn_circle_02") forState:UIControlStateNormal];    //选择要发布的圈子
        _circleTitleLabel.text = _L(@"title_circle_02");    //同时发布商品商讯
        
        _descTextView.layer.borderColor = [_SYS_COLOR_005 CGColor];
        _originField.borderStyle = UITextBorderStyleRoundedRect;
        _nameField.borderStyle = UITextBorderStyleRoundedRect;
        _priceField.borderStyle = UITextBorderStyleRoundedRect;
        _areaField.borderStyle = UITextBorderStyleRoundedRect;
        _numField.borderStyle = UITextBorderStyleRoundedRect;
        _deliveryCityTextField.borderStyle = UITextBorderStyleRoundedRect;
        _localFareTextField.borderStyle = UITextBorderStyleRoundedRect;
        _nationwideFareTextField.borderStyle = UITextBorderStyleRoundedRect;
    }
}

/*!
 @abstract 绘制出取货地址view
 当用户点击了自取的配送方式，那么在配送方式下方和圈子view上方应显示处取货地址view
 */
- (void)drawDeliveryAddressView
{
    
    //取货地址view
    _deliveryAddressView = [[UIView alloc] initWithFrame:CGRectMake(10.0f, _deliveryWayView.frame.origin.y
                                                                    + _deliveryWayView.frame.size.height + 5.0f, 300.0f, 0.0f)];
    _deliveryAddressView.backgroundColor = [UIColor whiteColor];
    _deliveryAddressView.layer.cornerRadius = 3;
    _deliveryAddressView.layer.borderWidth = 1;
    _deliveryAddressView.alpha = 0.0f;
    _deliveryAddressView.layer.borderColor = [_SYS_COLOR_003 CGColor];
    _deliveryAddressView.userInteractionEnabled = YES;
    UIGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addressLabelEvent:)];
    [_deliveryAddressView addGestureRecognizer:gestureRecognizer];
    
    [_scrollView addSubview:_deliveryAddressView];
    
    //取货地址label
    UILabel *addressTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10,8, 65, 20)];
    addressTitleLabel.font = _SYS_FONT_003;
    addressTitleLabel.text = _L(@"title_address_03");      //取货地址
    [_deliveryAddressView addSubview:addressTitleLabel];
    
    //地址显示栏
    _promptLabelInAddressView = [[UILabel alloc] initWithFrame:CGRectMake(addressTitleLabel.frame.origin.x+addressTitleLabel.frame.size.width+30.0f, 8.0f, 150.0f, 20.0f)];
    
    _promptLabelInAddressView.userInteractionEnabled = YES;
    _promptLabelInAddressView.text = _L(@"holder_45");
    _promptLabelInAddressView.textColor = _SYS_COLOR_003;
    _promptLabelInAddressView.font = _SYS_FONT_004;
    [_deliveryAddressView addSubview:_promptLabelInAddressView];

    //选项图标
    UIImageView *indcatorView = [[UIImageView alloc] initWithFrame:CGRectMake(300.0f-30.0f, 10.0f, 9.5f, 16.0f)];
    indcatorView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_icon_008@2x" ofType:@"png"]];
    
    [_deliveryAddressView addSubview:indcatorView];
    
    //画分割线
    UIImageView* line1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 35.0f, 300, 0.5f)];
    line1.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_bg_008@2x" ofType:@"png"]];
    
    [_deliveryAddressView addSubview:line1];
    
    //地址显示栏
    _addressLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, line1.frame.origin.y + line1.frame.size.height + 5.0f, 250.0f, 20.0f)];
    
    _addressLabel.userInteractionEnabled = YES;
    _addressLabel.text = _L(@"title_address_04");
    
    _addressLabel.textColor = _SYS_COLOR_003;
    _addressLabel.font = _SYS_FONT_004;
    [_deliveryAddressView addSubview:_addressLabel];

}

/*!
 @abstract 设置取货地址view是否显示
 如果选择了自取，则显示出取货地址,以及调整CircleView的位置
 */

- (void)showAddressView
{
    _deliveryAddressViewDidShow = YES;
    _deliveryAddressView.alpha = 1.0f;
    [self positioningViewAccurately];
}

- (void)hideAddressView
{
    _deliveryAddressViewDidShow = NO;
    _deliveryAddressView.alpha = 0.0f;
    [self positioningViewAccurately];
}

- (void)setAddressViewHidden
{
    NSTimeInterval animationDuration = 0.5f;
    [UIView beginAnimations:@"hideOrShowDeliveryAddressView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    if (_deliveryAddressView == nil) {
        [self drawDeliveryAddressView];
    }
    
    if ([_takeButton isSelected]) {
        [self showAddressView];
        [_scrollView setContentSize:CGSizeMake(_scrollView.contentSize.width, _scrollView.contentSize.height + 70.0f)];
        
    }else{
        
        [self hideAddressView];
        
        [_scrollView setContentSize:CGSizeMake(_scrollView.contentSize.width, _scrollView.contentSize.height - 70.0f)];
    }
    
    [UIView commitAnimations];
    
}

- (void)drawFreightView
{
    _freightView = [[UIView alloc] initWithFrame:CGRectMake(10, _deliveryWayView.frame.origin.y
                                                            + _deliveryWayView.frame.size.height + 5.0f, 300, 0.0f)];
    _freightView.backgroundColor = [UIColor whiteColor];
    _freightView.layer.cornerRadius = 3;
    _freightView.layer.borderWidth = 1;
    _freightView.alpha = 0.0f;
    _freightView.layer.borderColor = [_SYS_COLOR_003 CGColor];
    _freightView.userInteractionEnabled = YES;
    UIGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(freightLabelEvent:)];
    [_freightView addGestureRecognizer:gestureRecognizer];
    [_scrollView addSubview:_freightView];
    
    //取货地址label
    UILabel *addressTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 8, 65, 20)];
    addressTitleLabel.font = _SYS_FONT_003;
    addressTitleLabel.text = _L(@"vc_title_077");      //运费模板
    [_freightView addSubview:addressTitleLabel];
    
    //地址显示栏
    _promptLabelInFreightView = [[UILabel alloc] initWithFrame:CGRectMake(addressTitleLabel.frame.origin.x+addressTitleLabel.frame.size.width+30.0f, 8.0f, 150.0f, 20.0f)];
    
    _promptLabelInFreightView.userInteractionEnabled = YES;
    _promptLabelInFreightView.text = _L(@"holder_46");
    
    _promptLabelInFreightView.textColor = _SYS_COLOR_003;
    _promptLabelInFreightView.font = _SYS_FONT_004;
    [_freightView addSubview:_promptLabelInFreightView];
    
    //选项图标
    UIImageView *indcatorView = [[UIImageView alloc] initWithFrame:CGRectMake(300.0f-30.0f, 10.0f, 9.5f, 16.0f)];
    indcatorView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_icon_008@2x" ofType:@"png"]];
    
    [_freightView addSubview:indcatorView];
    
    //画分割线
    UIImageView* line1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 35.0f, 300, 0.5f)];
    line1.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_bg_008@2x" ofType:@"png"]];
    
    [_freightView addSubview:line1];
    
    //地址显示栏
    _freightLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, line1.frame.origin.y + line1.frame.size.height + 5.0f, 250.0f, 20.0f)];
    
    _freightLabel.userInteractionEnabled = YES;
    _freightLabel.text = _L(@"holder_42");
    
    _freightLabel.textColor = _SYS_COLOR_003;
    _freightLabel.font = _SYS_FONT_004;
    [_freightView addSubview:_freightLabel];
}

- (void)showFreightView
{
    _freightViewDidShow = YES;
    _freightView.alpha = 1.0f;
    [self freightViewNeedsLayout];
}

- (void)hideFreightView
{
    _freightViewDidShow = NO;
    _freightView.alpha = 0.0f;
    [self freightViewNeedsLayout];
}

- (void)setFreightViewHidden
{
    NSTimeInterval animationDuration = 0.5f;
    [UIView beginAnimations:@"hideOrShowDeliveryAddressView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    if (_freightView == nil) {
        [self drawFreightView];
        
    }
    
    if ([_expressButton isSelected]) {
        [self showFreightView];
        [_scrollView setContentSize:CGSizeMake(_scrollView.contentSize.width, _scrollView.contentSize.height + 70.0f)];
        
    }else{
        
        [self hideFreightView];
        
        [_scrollView setContentSize:CGSizeMake(_scrollView.contentSize.width, _scrollView.contentSize.height - 70.0f)];
    }
    
    [UIView commitAnimations];
}

/*!
 @abstract 如果运费模板view存在那么动画中要加上对取货地址view的frame的移动,同时也要动态的更新_scrollview的高度
 */
- (void)freightViewNeedsLayout
{
    if (_expressButton.isSelected) {
        
        _freightView.frame = CGRectMake(10, _deliveryWayView.frame.origin.y
                                        + _deliveryWayView.frame.size.height + 5.0f, 300, 70.0f);
        
        //如果取货地址显示了
        if (_deliveryAddressViewDidShow) {
            
            _deliveryAddressView.frame = CGRectMake(10.0f, _freightView.frame.origin.y
                                                    + _freightView.frame.size.height + 5.0f, 300.0f, 70.0f);
            _circleView.frame = CGRectMake(10, _deliveryAddressView.frame.origin.y
                                           + _deliveryAddressView.frame.size.height + 5.0f, 300, 75);
        }
        
        //如果取货地址没有显示
        else {
            _circleView.frame = CGRectMake(10, _freightView.frame.origin.y
                                           + _freightView.frame.size.height + 5.0f, 300, 75);
        }
        
    }else {
    
        //如果取货地址显示了
        if (_deliveryAddressViewDidShow) {
            
            _deliveryAddressView.frame = CGRectMake(10.0f, _deliveryWayView.frame.origin.y
                                                    + _deliveryWayView.frame.size.height + 5.0f, 300.0f, 70.0f);
            _circleView.frame = CGRectMake(10, _deliveryAddressView.frame.origin.y
                                           + _deliveryAddressView.frame.size.height + 5.0f, 300, 75);
        }
        
        //如果取货地址没有显示
        else {
            _circleView.frame = CGRectMake(10, _deliveryWayView.frame.origin.y
                                           + _deliveryWayView.frame.size.height + 5.0f, 300, 75);
        }
        _freightView.frame = CGRectMake(10, _deliveryWayView.frame.origin.y
                                        + _deliveryWayView.frame.size.height + 5.0f, 300, 0.0f);
        
    }
    
    _advView.frame = CGRectMake(10, _circleView.frame.origin.y + _circleView.frame.size.height + 5, 300, _circleView.frame.size.height);
}

/*!
 @abstract 裁剪选择后的图片
 */
- (void)cropImage:(UIImage *)image
{
    //获得图片后，进行裁剪
    GKImageCropper* cropper = [[GKImageCropper alloc] init];
    cropper.delegate = self;
    cropper.image = image;
    cropper.rescaleImage = false;
    cropper.dismissAnimated = YES;
    cropper.cropMethod = ImageCropMethodPreview;
    
    [self presentModalViewController:cropper animated:YES];
}

/*!
 @abstract 设置物流运费view的alpha值，以便完成显示或隐藏的动画。
 同时在resetview方法中，要将所有alpha值设为0。
 */
- (void)setAlphaFareForWhoView:(CGFloat)alpha
{
    _lineImageView_1.alpha = alpha;
    _fareLabel.alpha = alpha;
    _sellerButton.alpha = alpha;
    _sellerImageView.alpha = alpha;
    _sellerLabel.alpha = alpha;
    _buyerButton.alpha = alpha;
    _buyerImageView.alpha = alpha;
    _buyerLabel.alpha = alpha;
}

/*!
 @abstract 设置发货城市、同城运费和全国运费views的alpha值，以便完成显示或隐藏的动画。
 同时在resetview方法中，要将所有alpha值设为0。
 */
- (void)setAlphaFareView:(CGFloat)alpha
{
    _lineImageView_2.alpha = alpha;
    _deliveryCityLabel.alpha = alpha;
    _lineImageView_3.alpha = alpha;
    _localLabel.alpha = alpha;
    _localFareTextField.alpha = alpha;
    _deliveryCityTextField.alpha = alpha;
    _localUnitLabel.alpha = alpha;
    _nationwideLabel.alpha = alpha;
    _nationwideFareTextField.alpha = alpha;
    _nationwideUnitLabel.alpha = alpha;
}

/*!
 @abstract 显示物流运费view
 */
- (void)showFareForWhoView
{
    NSTimeInterval animationDuration = 0.5f;
    [UIView beginAnimations:@"showFareForWhoView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    _deliveryWayView.frame = CGRectMake(10, _areaView.frame.size.height + _areaView.frame.origin.y + 5.0f, 300, 160);
    
    [_scrollView setContentSize:CGSizeMake(_scrollView.contentSize.width, _scrollView.contentSize.height + 85.0f)];
    
    [self setAlphaFareForWhoView:1.0f];
    
    [self positioningViewAccurately];
    
    [UIView commitAnimations];
}

/*!
 @abstract 隐藏物流运费view
 */
- (void)hideFareForWhoView
{
    NSTimeInterval animationDuration = 0.5f;
    [UIView beginAnimations:@"hideFareForWhoView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    _deliveryWayView.frame = CGRectMake(10, _areaView.frame.size.height + _areaView.frame.origin.y + 5.0f, 300, 75);
    
    [_scrollView setContentSize:CGSizeMake(_scrollView.contentSize.width, _scrollView.contentSize.height - 85.0f)];
    
    [self setAlphaFareForWhoView:0.0f];
    
    [self positioningViewAccurately];
    
    [UIView commitAnimations];
}

/*!
 @abstract 显示发货城市、同城运费和全国运费views。
 */
- (void)showFareView
{
    NSTimeInterval animationDuration = 0.5f;
    [UIView beginAnimations:@"showFareView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    _deliveryWayView.frame = CGRectMake(10, _areaView.frame.size.height + _areaView.frame.origin.y + 5.0f, 300, 230);
    
    [_scrollView setContentSize:CGSizeMake(_scrollView.contentSize.width, _scrollView.contentSize.height + 70.0f)];
    
    [self setAlphaFareView:1.0f];
    
    [self positioningViewAccurately];
    
    [UIView commitAnimations];
}

/*!
 @abstract 隐藏发货城市和设置具体的物流费用view
 @param all 这个值主要是用来决定，是否应该调整_deliveryWayView的高度，如果all为YES，表示，此时高度不用调整，因为此时用户是在取消“卖家快递上门”时，在hideFareForWhoView方法中，已经将_deliveryWayView设为75，所以此处就不用设置；如果all为NO，那么表示，此时是取消了“买家承担运费”，选择了“卖家承担运费”，此时要隐藏发货城市及其以下的view，并且_deliveryWayView的高度要减去隐藏的view的高度，设置为160。
 */
- (void)hideFareView:(BOOL)all
{
    NSTimeInterval animationDuration = 0.5f;
    [UIView beginAnimations:@"hideFareView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    //当all为true时，表示同时“隐藏”物流运费以及下面的所有有关运费的view
    //否则只“隐藏”
    if (!all) {
        
        _deliveryWayView.frame = CGRectMake(10, _areaView.frame.size.height + _areaView.frame.origin.y + 5.0f, 300, 160);        
    }
    
    [_scrollView setContentSize:CGSizeMake(_scrollView.contentSize.width, _scrollView.contentSize.height - 70.0f)];
    [self setAlphaFareView:0.0f];
    
    [self positioningViewAccurately];
    
    [UIView commitAnimations];
}

/*!
 @abstract 如果取货地址view存在那么动画中要加上对取货地址view的frame的移动,同时也要动态的更新_scrollview的高度
 */
- (void)positioningViewAccurately
{
    if (_takeButton.isSelected) {
        
        //如果运费模板显示了
        if (_freightViewDidShow) {
            
            _freightView.frame = CGRectMake(10, _deliveryWayView.frame.origin.y
                                            + _deliveryWayView.frame.size.height + 5.0f, 300, 70.0f);
            
            _deliveryAddressView.frame = CGRectMake(10.0f, _freightView.frame.origin.y
                                                    + _freightView.frame.size.height + 5.0f, 300.0f, 70.0f);
            
            _circleView.frame = CGRectMake(10, _deliveryAddressView.frame.origin.y
                                           + _deliveryAddressView.frame.size.height + 5.0f, 300, 75);
        }
        
        //如果运费模板没有显示
        else {
            _deliveryAddressView.frame = CGRectMake(10.0f, _deliveryWayView.frame.origin.y
                                                    + _deliveryWayView.frame.size.height + 5.0f, 300.0f, 70.0f);
            
            _circleView.frame = CGRectMake(10, _deliveryAddressView.frame.origin.y
                                           + _deliveryAddressView.frame.size.height + 5.0f, 300, 75);
        }
        
    }else{
        
        _deliveryAddressView.frame = CGRectMake(10.0f, _deliveryWayView.frame.origin.y
                                                + _deliveryWayView.frame.size.height + 5.0f, 300.0f, 0.0f);
        //如果运费模板显示了
        if (_freightViewDidShow) {
            
            _freightView.frame = CGRectMake(10, _deliveryWayView.frame.origin.y
                                            + _deliveryWayView.frame.size.height + 5.0f, 300, 70.0f);
            
            _circleView.frame = CGRectMake(10, _freightView.frame.origin.y
                                           + _freightView.frame.size.height + 5.0f, 300, 75);
        }
        //如果运费模板没有显示
        else {
            _circleView.frame = CGRectMake(10, _deliveryWayView.frame.origin.y
                                           + _deliveryWayView.frame.size.height + 5.0f, 300, 75);
        }
    }
        
    _advView.frame = CGRectMake(10, _circleView.frame.origin.y + _circleView.frame.size.height + 5, 300, _circleView.frame.size.height);
}

/*!
 @abstract 实现物流运费选项的单选效果
 */
- (void)sellerPayFare:(BOOL)shouldPay
{
    [_sellerButton setSelected:shouldPay];
    [_buyerButton setSelected:!shouldPay];
    
    if (shouldPay) {
        _sellerImageView.image = [UIImage imageNamed:@"com_icon_014"];
        _buyerImageView.image = [UIImage imageNamed:@"com_icon_013"];
    }else{
        _sellerImageView.image = [UIImage imageNamed:@"com_icon_013"];
        _buyerImageView.image = [UIImage imageNamed:@"com_icon_014"];
    }
    
}

/*!
 @abstract 填充运费模板视图
 */
- (void)renderFreightView:(NSDictionary *)freight
{
    _currentFreight = freight;
    _currentFreightId = [freight[@"id"] integerValue];
    
    if ([freight[@"type"] integerValue]) {
        //买家承担运费
        _freightLabel.text = [NSString stringWithFormat:@"%@ %@",_currentFreight[@"name"],_L(@"title_fare_bear_01")];
    } else {
        //卖家承担运费
        _freightLabel.text = [NSString stringWithFormat:@"%@ %@",_currentFreight[@"name"],_L(@"title_fare_bear_02")];
    }
    
    _promptLabelInFreightView.text = _L(@"holder_44");
    
}

#pragma mark - 事件

/*!
 @abstract 拾取取货地址事件
 */
- (void)addressLabelEvent:(id)sender
{
    AddressPickerViewController *addressPickerViewVC;
    if (![_address isEqual:[NSNull null]]) {
        addressPickerViewVC = [[AddressPickerViewController alloc] initWithSelectedSelectedAddrId:[_address[@"id"] integerValue]];
    }
    else {
        addressPickerViewVC = [[AddressPickerViewController alloc] init];
    }
    addressPickerViewVC.delegate = self;

    [self.navigationController pushViewController:addressPickerViewVC animated:YES];
}

- (void)freightLabelEvent:(id)sender
{
    FreightPickerViewController *freightPickerViewVC= [[FreightPickerViewController alloc] initWithSelectedFreightId:[_currentFreight[@"id"] integerValue]];
    freightPickerViewVC.delegate = self;

    [self.navigationController pushViewController:freightPickerViewVC animated:YES];
}

/*!
 @abstract 返回按钮事件
 */
- (void) backButtonEvent
{
//由于功能<广告>的增加，VC堆栈改变，push本VC，因此改为了pop出去
//    if (_product == nil) {
//        [self.navigationController dismissModalViewControllerAnimated:true];
//    }
//    else {
//        [self.navigationController popViewControllerAnimated:true];
//    }
    
    
    //根据按钮状态，获取当前的deliveryMode
    int deliveryMode = 3;
    
    //快递方式
    if (_expressButton.selected == YES && _takeButton.selected == NO) {
        
        deliveryMode = 1;
    }
    //自取方式
    else if (_expressButton.selected == NO && _takeButton.selected == YES){
        
        deliveryMode = 0;
    }
    //快递或者自取方式
    else if (_expressButton.selected == YES && _takeButton.selected == YES){
        
        deliveryMode = 2;
    }
    
    else {
        deliveryMode = 3;
    }
    
    if (_product == nil) {
        
        if ([_nameField.text length] == 0 &&
            [_descTextView.text length] == 0 &&
            [_originField.text length] == 0 &&
            [_imageUpload count] == 0 &&
            ([_priceField.text isEqualToString:@"1"]) &&
            ([_unitLabel.text isEqualToString:@"元/斤"]) &&
            [_numField.text length] == 0 &&
            [_areaField.text length] == 0 &&
            (deliveryMode == 3))
        {
            
            [self.navigationController popViewControllerAnimated:true];
        }
        else {
            UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_90") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];
            alertView.tag = 2;
            [alertView show];
        }
    }
    
    else {
        
#warning 此处图片判断尚未添加
        if ([_nameField.text isEqualToString:_product[@"name"]] &&
            [_descTextView.text isEqualToString:_product[@"description"]] &&
            [_originField.text isEqualToString:_product[@"provenance"]] &&
            [_priceField.text isEqualToString:[NSString stringWithFormat:@"%@", _product[@"price"]]] &&
            [_unitLabel.text isEqualToString:[NSString stringWithFormat:_L(@"title_unit_01"), _product[@"unitName"]]] &&
            [_numField.text isEqualToString:[NSString stringWithFormat:@"%.f", [_product[@"inventory"] doubleValue]]] &&
            [_areaField.text isEqualToString:_product[@"salesRegion"]] &&
            [_product[@"deliveryMode"] intValue] == deliveryMode)
        {
            
            [self.navigationController popViewControllerAnimated:true];
        }
        
        else {
            UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_91") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];
            alertView.tag = 3;
            [alertView show];
        }
    }
    
    
}

/*!
 @abstract 删除按钮事件
 */
- (void)removeButtonEvent
{
    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_15") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_delete_06"), nil];
    alertView.tag = 1;
    [alertView show];
}

/*!
 @abstract 继续销售按钮事件
 */
- (void)sellingButtonEvent
{
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_PRODUCT_CHANGE_STATUS_SALE];
    [request setValue:[_product valueForKey:@"id"] forParameter:@"productId"];
    NSDictionary* dict = [request synchronous];
    
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    if (jmf.status == JMStatusSucceed) {
        [Helper showAllTextDialog:_L(@"alert_74") inView:nil];
        [self.navigationController popViewControllerAnimated:true];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

///*!
// @abstract 继续销售按钮事件
// */
//- (void)fieldTouchEvent:(id)sender
//{
//    _nameField.borderStyle = UITextBorderStyleNone;
//    _priceField.borderStyle = UITextBorderStyleNone;
//    _areaField.borderStyle = UITextBorderStyleNone;
//    
//    UITextField* currentField = (UITextField *)sender;
//    currentField.borderStyle = UITextBorderStyleRoundedRect;
//    
//    [_areaField resignFirstResponder];
//    
//    
//}


/*!
 @abstract 停止销售按钮事件
 */
- (void)stopSellingButtonEvent
{
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_PRODUCT_CHANGE_STATUS_STOP];
    [request setValue:[_product valueForKey:@"id"] forParameter:@"productId"];
    NSDictionary* dict = [request synchronous];
    
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    if (jmf.status == JMStatusSucceed) {
        [Helper showAllTextDialog:_L(@"alert_73") inSeconds:3];
        [self.navigationController popViewControllerAnimated:true];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}


/*!
 @abstract 推广按钮点击事件
 推广按钮被点击后，会设定_advButtonOnClick=true，然后调用saveButtonEvent
 */
- (void)advButtonEvent
{
    _advButtonOnClick = true;
    [self saveButtonEvent];
}


/*!
 @abstract 保存按钮事件
 */
- (void)saveButtonEvent
{
    [_nameField resignFirstResponder];
    [_descTextView resignFirstResponder];
    [_originField resignFirstResponder];
    [_priceField resignFirstResponder];
    [_areaField resignFirstResponder];
    [_numField resignFirstResponder];
    
    
    //按照表单顺序验证字段
    
    //商品名称
    if (_nameField.text.length == 0) {
        [Helper showAlertWithTitle:nil andMessage:_L(@"alert_60")];
        return;
    }
    
    //商品介绍
    if (_descTextView.text.length == 0) {
        [Helper showAlertWithTitle:nil andMessage:_L(@"alert_61")];
        return;
    }
    
    //产地
    if (_originField.text.length == 0) {
        [Helper showAlertWithTitle:nil andMessage:_L(@"alert_62")];
        return;
    }
    
    //图片
    if (_image1 == nil && _image2 == nil && _image3 == nil) {
        [Helper showAlertWithTitle:nil andMessage:_L(@"alert_12")];
        return;
    }
    
    //商品价格
    if (![Helper testNumberWithString:_priceField.text]) {
        [Helper showAlertWithTitle:nil andMessage:_L(@"alert_14")];    //请输入正确的商品价格，支持两位小数
        return;
    }
    
    //库存
    if(_numField.text.length == 0) {
        [Helper showAlertWithTitle:nil andMessage:_L(@"alert_63")];
        return;
    }
    if ([_numField.text doubleValue] <= 0){
        [Helper showAlertWithTitle:nil andMessage:_L(@"alert_68")];
        return;
    }
    
    //销售区域
    if (_areaField.text.length == 0) {
        [Helper showAlertWithTitle:nil andMessage:_L(@"alert_64")];
        return;
    }
    
    //交货方式
    if (_expressButton.selected == NO && _takeButton.selected == NO) {
        [Helper showAlertWithTitle:nil andMessage:_L(@"alert_65")];
        return;
    }
    //快递方式
    if (_expressButton.selected == YES) {
        
        if (_currentFreight == nil) {
            
            [Helper showAlertWithTitle:nil andMessage:_L(@"alert_113")];
            return;
        }
    }
    //自取方式
    if (_takeButton.selected == YES){
        
        if (_address == nil || [_address isEqual:[NSNull null]]) {
            [Helper showAlertWithTitle:nil andMessage:_L(@"alert_13")];
            return;
        }
    }

    JSONRequest* request = [[JSONRequest alloc] init];
    [request setValue:_ACCOUNT_TOKEN     forParameter:@"token"];
    [request setValue:_nameField.text    forParameter:@"name"];
    [request setValue:_descTextView.text forParameter:@"description"];
    [request setValue:_priceField.text   forParameter:@"price"];
    [request setValue:_originField.text  forParameter:@"provenance"];
    [request setValue:_areaField.text    forParameter:@"salesRegion"];
    [request setValue:_numField.text     forParameter:@"count"];
    [request setValue:[_unitLabel.text substringFromIndex:2] forParameter:@"unitName"];
    
    for (int i = 0; i < _imageUpload.count; i++) {
        
        UIImage* image = [_imageUpload objectAtIndex:i];

        if (i == 0) {
            [request setValue:image forParameter:@"image1"];
        }
        if (i == 1) {
            [request setValue:image forParameter:@"image2"];
        }
        if (i == 2) {
            [request setValue:image forParameter:@"image3"];
        }

    }
    
    if (_circleIDString != nil && _circleIDString.length > 0) {
        [request setValue:_circleIDString forParameter:@"circleIds"];
    }
    
    if (_product != nil) {
        [request setValue:[_product valueForKey:@"id"] forParameter:@"productId"];
    }
    
    //根据按钮状态，判断deliveryMode
    NSString *deliveryMode = nil;
    
    //快递方式
    if (_expressButton.selected == YES && _takeButton.selected == NO) {
        
        deliveryMode = @"1";
        [request setValue:[NSNumber numberWithInteger:_currentFreightId] forParameter:@"freightId"];
    }
    //自取方式
    else if (_expressButton.selected == NO && _takeButton.selected == YES){
        
        deliveryMode = @"0";
    }
    //快递或者自取方式
    else if (_expressButton.selected == YES && _takeButton.selected == YES){
        
        deliveryMode = @"2";
        [request setValue:[NSNumber numberWithInteger:_currentFreightId] forParameter:@"freightId"];
    }
    
    [request setValue:deliveryMode forParameter:@"deliveryMode"];

    //如果用户选择的是 “自取” 或者 “快递或自取”   那么必传一个地址
    if (deliveryMode != nil && ![deliveryMode isEqualToString:@"1"]) {
        
        if ([_address isEqual:[NSNull null]] ) {
            [Helper showAlertWithTitle:nil andMessage:_L(@"alert_13")];
            return;
        }
        
        [request setValue:[_address objectForKey:@"id"] forParameter:@"consigneeId"];
    }
    
//    //如果用户选择了“快递”或者“快递或者自取”  那么就必选有谁来承担运费
//    //用户选择了卖家承担运费，就无需填其它的项；如果选择了买家承担运费，那么用户就还要填写发货城市 同城的运费 以及 全国的运费
//    
//    //谁承担运费,默认卖家承担
//    NSInteger fareForWho = 0;
//    
//    if (deliveryMode != nil && ![deliveryMode isEqualToString:@"0"]) {
//        
//        //如果是买家承担运费
//        if(!_sellerButton.isSelected && _buyerButton.isSelected)
//        {            
//            fareForWho = 1;
//        }
//        
//        if (fareForWho == 1) {
//            //此时为“买家承担运费”，要求用户必填的信息
//            [request setValue:_deliveryCityTextField.text forParameter:@"shipCity"];
//            [request setValue:_localFareTextField.text forParameter:@"cityFreight"];
//            [request setValue:_nationwideFareTextField.text forParameter:@"nationalFreight"];
//        }
//        
//        [request setValue:[NSString stringWithFormat:@"%d", fareForWho] forParameter:@"bearTheFreight"];
//    }
    
    
    if (_imageDelIds.count > 0) {

        [request setValue:[_imageDelIds componentsJoinedByString:@","] forParameter:@"pictureInfoIds"];
    }
    
    if (_product == nil) {
        request.URLString = _JSON_URL_PRODUCT_ADD;
        
//        if (_image1 == nil && _image2 == nil && _image3 == nil) {
//            [Helper showAlertWithTitle:nil andMessage:_L(@"alert_12")];   //请选择一个产品图片
//            return;
//        }
    }
    else {
        request.URLString = _JSON_URL_PRODUCT_CHANGE_INFO;
    }
    
    request.delegate = self;
    request.hudOn = true;
    request.hudTitle = _L(@"title_loading_05");
    request.requestMode = RequestModeMultiPart;
    [request asynchronous];

}

/*!
 @abstract 选择圈子按钮事件
 */
- (void)circleButtonEvent
{
    CirclePickerViewController* circlePickerViewController = [[CirclePickerViewController alloc] initWithStyle:UITableViewStyleGrouped];
    circlePickerViewController.delegate = (id)self;
    
    UINavigationController* circleNavigationController = [[UINavigationController alloc] initWithRootViewController:circlePickerViewController];

    [Helper navigationControllerCommonStyle:circleNavigationController];
    
    [self.navigationController presentModalViewController:circleNavigationController animated:true];
}


/*!
 @abstract 商品单位按钮事件
 */
- (void)unitButtonEvent
{
    //移除其它焦点
    [_nameField resignFirstResponder];
    [_descTextView resignFirstResponder];
    [_originField resignFirstResponder];
    [_priceField resignFirstResponder];
    [_areaField resignFirstResponder];
    [_numField resignFirstResponder];
    
    //点击后删除之前的PickerView
    for (UIView *view in self.view.subviews) {
        if ([view isKindOfClass:[UICustomPickerView class]]) {
            [view removeFromSuperview];
        }
    }
    _unitPickerView = [[UICustomPickerView alloc] initWithFrame:CGRectMake(0,_SYS_FRAME_HEIGHT - 260-44, 320, 260)];
    _unitPickerView.delegate = self;
    _unitPickerView.dataSource = self;
    [self.view addSubview:_unitPickerView];
    [_unitPickerView pickerShow:UICustomPickerViewNormalType];
}


/*!
 @abstract 图片按钮事件
 */
- (void)imageButtonEvent:(id)sender
{
    UIButton *selectedButton = (UIButton *)sender;
    
    
    UIActionSheet *actionSheet;
    if ((selectedButton.tag == 1 && _image1 != nil) || (selectedButton.tag == 2 && _image2 != nil) || (selectedButton.tag == 3 && _image3 != nil)) {
        actionSheet = [[UIActionSheet alloc] initWithTitle:@"" delegate:self cancelButtonTitle:_L(@"btn_no_01") destructiveButtonTitle:nil otherButtonTitles:_L(@"btn_photo_01"), _L(@"btn_photo_02"), _L(@"btn_photo_03"), nil];
        actionSheet.destructiveButtonIndex = 2;
    }
    else {
        actionSheet = [[UIActionSheet alloc] initWithTitle:@"" delegate:self cancelButtonTitle:_L(@"btn_no_01") destructiveButtonTitle:nil otherButtonTitles:_L(@"btn_photo_01"), _L(@"btn_photo_02"), nil];
    }
    
    actionSheet.tag = selectedButton.tag;
    [actionSheet showInView:self.view];
}

/*!
 @abstract 配送方式选中标记与未被选中标记切换
 */
- (void)switchDeliveryWayButtonEvent:(id)sender
{
    UIButton *selectedButton = (UIButton *)sender;
    UIImageView *selectedImageView = [[selectedButton subviews] objectAtIndex:0];
    
    //判断该按钮是否已经被选中，如果已经被选中，那么就变成相反的状态
    if ([selectedButton isSelected]) {
        
        
        selectedImageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_icon_010@2x" ofType:@"png"]];
        [selectedButton setSelected:NO];
        
    }else{
        
        selectedImageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_icon_011@2x" ofType:@"png"]];
        [selectedButton setSelected:YES];
    }
    
    //点击的是自取button才对取货地址view是否隐藏有反应
    if (selectedButton.tag == takeType) {
        [self setAddressViewHidden];
    }
    
    if (selectedButton.tag == expressType) {
        [self setFreightViewHidden];
    }
}

#pragma mark - HZAreaPicker delegate
- (void)customPickerView:(UICustomPickerView *)customPickerView areaStringReceived:(NSString *)area
{
    //获得被选中的地址
    if (customPickerView.tag == 98) {
         _areaField.text = area;
    }
    else if (customPickerView.tag == 96) {
        _deliveryCityTextField.text = area;
    }
    
    //隐藏选择器
    [_areaField resignFirstResponder];
    [_deliveryCityTextField resignFirstResponder];
    
    //将输入区域样式设为无边框
    if (_product != nil) {
        _areaField.borderStyle = UITextBorderStyleNone;
        _deliveryCityTextField.borderStyle = UITextBorderStyleNone;
    }
    
    //动画控制恢复scrollview的frame
//    [self recoverScrollView];
}

- (void)customPickerViewDidDismiss:(UICustomPickerView *)customPickerView
{
    //动画控制恢复scrollview的frame
//    [self recoverScrollView];
    
    //隐藏选择器
    [_areaField resignFirstResponder];
    [_deliveryCityTextField resignFirstResponder];
    
    //将输入区域样式设为无边框
    if (_product != nil) {
        _areaField.borderStyle = UITextBorderStyleNone;
        _deliveryCityTextField.borderStyle = UITextBorderStyleNone;
    }
}


#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (actionSheet.tag) {
        case 1:
            _currentImageButton = _imageButton1;
            break;
        case 2:
            _currentImageButton = _imageButton2;
            break;
        case 3:
            _currentImageButton = _imageButton3;
            break;
            
        default:
            break;
    }

#warning 需要优化，算法太硬，建议为每个图片对象，封装成类，并对3个图片对象，封装为array
    //2=选择了删除
    if (buttonIndex == 2) {
        if (actionSheet.tag == 1) {
            
            [_imageDelIds addObject:[NSString stringWithFormat:@"%d", _imageId1]];
            [_imageUpload removeObject:_image1];
            
            if (_image3 != nil) {
                _image1 = _image2;
                _imageId1 = _imageId2;
                _image2 = _image3;
                _imageId2 = _imageId3;
                _image3 = nil;
                _imageId3 = 0;

                [_imageButton1 setImage:_image1 forState:UIControlStateNormal];
                [_imageButton2 setImage:_image2 forState:UIControlStateNormal];
                [_imageButton3 setImage:[UIImage imageNamed:@"transaction_btn_001"] forState:UIControlStateNormal];
            }
            else if (_image3 == nil && _image2 != nil) {
                _image1 = _image2;
                _imageId1 = _imageId2;
                _image2 = nil;
                _imageId2 = 0;
                
                [_imageButton1 setImage:_image1 forState:UIControlStateNormal];
                [_imageButton2 setImage:[UIImage imageNamed:@"transaction_btn_001"] forState:UIControlStateNormal];
                _imageButton3.hidden = true;
            }
            else {
                _image1 = nil;
                _imageId1 = 0;
            
                [_imageButton1 setImage:[UIImage imageNamed:@"transaction_btn_001"] forState:UIControlStateNormal];
                _imageButton2.hidden = true;
            }
        }
        else if (actionSheet.tag == 2) {
            
            [_imageDelIds addObject:[NSString stringWithFormat:@"%d", _imageId2]];
            [_imageUpload removeObject:_image2];
            
            if (_image3 != nil) {
                _image2 = _image3;
                _imageId2 = _imageId3;
                _image3 = nil;
                _imageId3 = 0;
                
                [_imageButton2 setImage:_image2 forState:UIControlStateNormal];
                [_imageButton3 setImage:[UIImage imageNamed:@"transaction_btn_001"] forState:UIControlStateNormal];
            }
            else if (_image3 == nil && _image2 != nil) {
                _image2 = nil;
                _imageId2 = 0;
                [_imageButton2 setImage:[UIImage imageNamed:@"transaction_btn_001"] forState:UIControlStateNormal];
                _imageButton3.hidden = true;
            }
            
        }
        else {
            [_imageDelIds addObject:[NSString stringWithFormat:@"%d", _imageId3]];
            [_imageUpload removeObject:_image3];
            
            _image3 = nil;
            _imageId3 = 0;
            
            [_imageButton3 setImage:[UIImage imageNamed:@"transaction_btn_001"] forState:UIControlStateNormal];
        }
    }
    //0/1=拍照和相册
    else {
        UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        //拍照模式
        if (buttonIndex == 0) {
            
            //判断摄像头是否可用
            if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
                imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            }else{
                imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            }
            
            [self presentModalViewController:imagePicker animated:YES];
            
            //访问相册模式
        }else if (buttonIndex == 1){
            imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            imagePicker.allowsEditing = NO;
            [self presentModalViewController:imagePicker animated:YES];
        }
    }
}


#pragma mark - 系统图片拾取器代理

-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
    [picker dismissModalViewControllerAnimated:NO];
    
    UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    [self cropImage:image];
}

- (void)imageCropperDidFinish:(GKImageCropper *)imageCropper withImage:(UIImage *)image
{
    //压缩图片
    UIImage *newImage = [Helper resizeImage:image forStyle:PictureStyleFullScreen];
    NSData *imageData = [Helper compressImageData:newImage withStyle:PictureStyleNormal];
    UIImage* compressedImage = [UIImage imageWithData:imageData];

    [_currentImageButton setImage:image forState:UIControlStateNormal];
    
    if (_currentImageButton.tag == 1) {
        [_imageDelIds addObject:[NSString stringWithFormat:@"%d", _imageId1]];   //加入要删除的图片ID
        [_imageUpload removeObject:_image1];    //从上传图片队列中，尝试删除一个图片

        _image1 = compressedImage;
        _imageButton2.hidden = false;
    }
    
    if (_currentImageButton.tag == 2) {
        [_imageDelIds addObject:[NSString stringWithFormat:@"%d", _imageId2]];
        [_imageUpload removeObject:_image2];
        
        _image2 = compressedImage;
        _imageButton3.hidden = false;
    }
    
    if (_currentImageButton.tag == 3) {
        [_imageDelIds addObject:[NSString stringWithFormat:@"%d", _imageId3]];
        [_imageUpload removeObject:_image3];
        
        _image3 = compressedImage;
    }

    [_currentImageButton setImage:compressedImage forState:UIControlStateNormal];
    
    //加入要上传的图片
    [_imageUpload addObject:compressedImage];
}


#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    [textField resignFirstResponder];

    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField.tag == 100) {
        
        if (![Helper testNumberWithString:[textField.text stringByAppendingString:string]]) {
            [Helper showAlertWithTitle:nil andMessage:_L(@"alert_14")];    //请输入正确的商品价格，支持两位小数
            return NO;
        }
    }
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (_product != nil) {
        textField.borderStyle = UITextBorderStyleRoundedRect;
    }
    
    //点击后删除之前的PickerView
    for (UIView *view in self.view.subviews) {
        if ([view isKindOfClass:[UICustomPickerView class]]) {
            [view removeFromSuperview];
        }
    }
    
    //如果是地址textfield 那么就是弹出城市数据选择器
    if (textField.tag == 99) {
        
        [_nameField resignFirstResponder];
        [_descTextView resignFirstResponder];
        [_originField resignFirstResponder];
        [_priceField resignFirstResponder];
        [_numField resignFirstResponder];
        [_deliveryCityTextField resignFirstResponder];
        [_localFareTextField resignFirstResponder];
        [_nationwideFareTextField resignFirstResponder];

        _customPickerView = [[UICustomPickerView alloc] initWithFrame:CGRectMake(0,_SYS_FRAME_HEIGHT - 260-44, 320, 260)];
        _customPickerView.tag = 98;
        _customPickerView.delegate = self;
        _customPickerView.location = textField.text;
        _customPickerView.hzAreaPickerStyle = HZAreaPickerWithStateAndCityAndDistrict;
        _customPickerView.areaPickerOption = HZAreaPickerInitNormalOption;
        
        [self.view addSubview:_customPickerView];
        [_customPickerView pickerShow:UICustomPickerViewAreaType];
        
        return NO;
    }
    
    //发货城市textfield
    else if (textField.tag == 97) {
        
        [_nameField resignFirstResponder];
        [_descTextView resignFirstResponder];
        [_originField resignFirstResponder];
        [_areaField resignFirstResponder];
        [_priceField resignFirstResponder];
        [_numField resignFirstResponder];
        [_localFareTextField resignFirstResponder];
        [_nationwideFareTextField resignFirstResponder];
        
        _customPickerView = [[UICustomPickerView alloc] initWithFrame:CGRectMake(0,_SYS_FRAME_HEIGHT - 260-44, 320, 260)];
        _customPickerView.tag = 96;
        _customPickerView.delegate = self;
        _customPickerView.location = textField.text;
        _customPickerView.hzAreaPickerStyle = HZAreaPickerWithStateAndCity;
        _customPickerView.areaPickerOption = HZAreaPickerInitNormalOption;
        
        [self.view addSubview:_customPickerView];
        [_customPickerView pickerShow:UICustomPickerViewAreaType];
        
        return NO;
    }

    _offset = _scrollView.contentOffset.y;
    [_scrollView setContentSize:CGSizeMake(_scrollView.contentSize.width, _scrollView.contentSize.height + (246-180))];
    
    //原始滑动距离增加键盘高度
    CGPoint pt = [textField convertPoint:CGPointMake(0, 0) toView:_scrollView];//把当前的textField的坐标映射到scrollview上
    
    if(_scrollView.contentOffset.y-pt.y+44<=0)//判断最上面不要去滚动
        
        [_scrollView setContentOffset:CGPointMake(0, pt.y-80) animated:YES];
    
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (_product != nil) {
        textField.borderStyle = UITextBorderStyleNone;
    }
    
    
    if (textField.tag == 95 || textField.tag == 96 || textField.tag == 97 || textField.tag == 86 || textField.tag == 100) {
        //开始动画
        [UIView beginAnimations:nil context:nil];
        //设定动画持续时间
        [UIView setAnimationDuration:0.3];

        [_scrollView setContentSize:CGSizeMake(_scrollView.contentSize.width, _scrollView.contentSize.height - (246-180))];
        [_scrollView setContentOffset:CGPointMake(0, _offset) animated:YES];
        //动画结束
        [UIView commitAnimations];
    }
}

#pragma mark - CustomPickerView DataSource

- (NSInteger)customPickerView:(UICustomPickerView *)customPickerView
      numberOfRowsInComponent:(NSInteger)component
{
    return _unitDataSource.count;
}

- (NSInteger)numberOfComponentsInUICustomPickerView:(UICustomPickerView *)customPickerView
{
    return 1;
}

#pragma mark - CustomPickerView Delegate

- (NSString *)customPickerView:(UICustomPickerView *)customPickerView titleForRow:(NSInteger)row
                  forComponent:(NSInteger)component
{
    NSString* unit = (NSString *)[[_unitDataSource objectAtIndex:row] valueForKey:@"name"];

    return unit;
}


- (void)customPickerView:(UICustomPickerView *)customPickerView didSelectRow:(NSInteger)row
             inComponent:(NSInteger)component
{
    _unitLabel.text = [NSString stringWithFormat:_L(@"title_unit_01"),[[_unitDataSource objectAtIndex:row] valueForKey:@"name"]];   //@"元/%@"
}


#pragma mark - CirclePickerDelegate

- (void)circlesPicked:(NSArray *)circles
{
    NSMutableArray* names = [[NSMutableArray alloc] init];
    NSMutableArray* ids = [[NSMutableArray alloc] init];

    for (NSDictionary* circle in circles) {
        [names addObject:[circle objectForKey:@"name"]];
        [ids addObject:[NSString stringWithFormat:@"%i", [[circle objectForKey:@"id"] integerValue]]];
    }
    
    _circleLabel.text = [names componentsJoinedByString:@" "];
    _circleIDString = [ids componentsJoinedByString:@","];
}


#pragma mark - JSONRequestDelegate

- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];

    if (jmf.status == JMStatusSucceed) {
        
        //根据_advButtonEvent状态判断下一步动作
        
        //如果_advButtonOnClick=false，那么说明点击的保存按钮，直接返回前一个页面
        if (!_advButtonOnClick) {
            
            [self.navigationController popViewControllerAnimated:true];
        }
        //否则=true，说明点击的是推广按钮，则继续请求
        else {
            
            //如果_product=nil，那么说明是新增，要对_product[id]赋值，以便向服务器请求推广验证时检测
            if (_product == nil) {
                
                _product = @{@"id" : [jmf numberValue:@"id"]};
            }
            
            JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_ADV_CHECK];
            request.delegate = self;
            request.hudOn = true;
            request.hudTitle = _L(@"alert_58");
            request.successSelector = @selector(advCheckSuccessSelector:);
            [request setValue:_product[@"id"] forParameter:@"productId"];
            [request asynchronous];
        }
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

//
- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}

- (void)getProductInfoSelector:(NSDictionary *)dict
{    
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        //已发圈子
        NSArray* oldCircles = [[dict valueForKey:@"data"] objectForKey:@"circles"];

        NSMutableArray* circleNames = [[NSMutableArray alloc] init];
        
        for (NSDictionary* aCircle in oldCircles) {
            [circleNames addObject:[aCircle valueForKey:@"name"]];
            
        }
        
        _circleLabel.text = [circleNames componentsJoinedByString:@" "];
        
        
        _product = [[dict valueForKey:@"data"] valueForKey:@"product"];

        _nameField.text = [_product valueForKey:@"name"];
        _descTextView.text = [_product valueForKey:@"description"];
        _originField.text = [_product valueForKey:@"provenance"];
        _numField.text = [NSString stringWithFormat:@"%.f", [[_product valueForKey:@"inventory"] doubleValue]];
        _priceField.text = [NSString stringWithFormat:@"%@", [_product valueForKey:@"price"]];
        _areaField.text = [_product valueForKey:@"salesRegion"];
        _unitLabel.text = [NSString stringWithFormat:_L(@"title_unit_01"), [_product valueForKey:@"unitName"]];
        
        if ([[_product valueForKey:@"status"] integerValue] == 0) {
            _stopSellingButton.hidden = false;
        }
        else {
            _sellingButton.hidden = false;
        }
        
        //初始化一个用于保存最初从服务器请求下来的图片数组，用于点击返回时，判断用户是否修改过图片
        if (_primeImagesData == nil) {
            _primeImagesData = [[NSMutableArray alloc] init];
        }
        if (_primeImagesData.count != 0) {
            [_primeImagesData removeAllObjects];
        }
        
        NSArray* pictures = [_product valueForKey:@"pictures"];
        
        
        for (int i = 0; i < pictures.count; i++) {
            
            NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[pictures objectAtIndex:i] valueForKey:@"previewUrl"]]];

            [_primeImagesData addObject:[UIImage imageWithData:data]];
            
            if (i == 0) {
                _image1 = [UIImage imageWithData:data];
                _imageId1 = [[[pictures objectAtIndex:i] objectForKey:@"id"] intValue];
                [_imageButton1 setImage:_image1 forState:UIControlStateNormal];
            }
            else if (i == 1) {
                _image2 = [UIImage imageWithData:data];
                _imageId2 = [[[pictures objectAtIndex:i] objectForKey:@"id"] intValue];
                [_imageButton2 setImage:_image2 forState:UIControlStateNormal];
            }
            else if (i == 2) {
                _image3 = [UIImage imageWithData:data];
                _imageId3 = [[[pictures objectAtIndex:i] objectForKey:@"id"] intValue];
                [_imageButton3 setImage:_image3 forState:UIControlStateNormal];
            }
        }
        
        //如果商品存在，且取货地址存在，就要绘出来
        if (![[_product objectForKey:@"consignee"] isKindOfClass:[NSNull class]]) {
            
            _address = [_product objectForKey:@"consignee"];
            
            NSString *address = [[_product objectForKey:@"consignee"] objectForKey:@"address"];
            
            _consIdSelected = [NSNumber numberWithInt:[[[_product objectForKey:@"consignee"] objectForKey:@"id"] integerValue]];
            
            _addressLabel.text = [NSString stringWithFormat:@"%@", address ? address : @""];
            _promptLabelInAddressView.text = _L(@"holder_43");
        }
        
        //设置运费模板
        if ([dict[@"data"][@"product"][@"deliveryMode"] integerValue] != 0 && dict[@"data"][@"freightTemplate"] != nil && ![dict[@"data"][@"freightTemplate"] isEqual:[NSNull null]]) {
            
            [self renderFreightView:dict[@"data"][@"freightTemplate"]];
        }
        
    }
    else {
//        _circleLabel.text = @"";
        [Helper easyShowJMFStatus:jmf];
    }
}

/*!
 @abstract 查询推广是否可用后，成功时调用的代理方法
 */
- (void)advCheckSuccessSelector:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];

    if (jmf.status == JMStatusSucceed) {
        
        //如果服务器范围的data[status]>0，说明不能申请，则提示用户
        if ([jmf integerValue:@"status"] > 0) {
            
            [Helper showAlertWithTitle:nil andMessage:[jmf stringValue:@"tips"]];
        }
        else {
            //组合参数
            NSMutableDictionary* data = [NSMutableDictionary dictionaryWithDictionary:jmf.data];
            [data setValue:_product[@"id"] forKey:@"id"];
            
            ProductAdvViewController* productAdvViewController = [[ProductAdvViewController alloc] initWithData:data];
            [self.navigationController pushViewController:productAdvViewController animated:true];
        }
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

#pragma mark - AddressPickerViewControllerDelegate

- (void)addressPicked:(NSDictionary *)consignee
{
    _consignee = consignee;
    _address = consignee;
    _addressLabel.text = [NSString stringWithFormat:@"%@%@", consignee[@"region"], consignee[@"address"]];
    
    _promptLabelInAddressView.text = _L(@"holder_43");
}

#pragma mark - UITextView Delegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"])
    {
        [_descTextView resignFirstResponder];
        return NO;
    }
    
//    if (textView.text.length > 140) {
//        
//        [Helper showAlertWithTitle:nil andMessage:_L(@"alert_11")];   //您填写的商品介绍已经超过140字了，不能再添加了哟
//        
//        textView.text = [textView.text substringToIndex:140];
//        
//        return NO;
//    }
    
    return YES;
}


- (void)textViewDidEndEditing:(UITextView *)textView
{
    if (_product != nil) {
        textView.layer.borderColor = [[UIColor whiteColor] CGColor];
    }
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    
    //点击后删除之前的PickerView
    for (UIView *view in self.view.subviews) {
        if ([view isKindOfClass:[UICustomPickerView class]]) {
            [view removeFromSuperview];
        }
    }
    
    if (_product != nil) {
        textView.layer.borderColor = [_SYS_COLOR_005 CGColor];
    }
}

- (void)textViewDidChange:(UITextView *)textView
{
    if ([textView.text length] > 140) {
        
        [Helper showAlertWithTitle:nil andMessage:_L(@"alert_11")];   //您填写的商品介绍已经超过140字了，不能再添加了哟
        
        textView.text = [textView.text substringToIndex:140];
    }
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_nameField resignFirstResponder];
    [_descTextView resignFirstResponder];
    [_originField resignFirstResponder];
    [_priceField resignFirstResponder];
    [_numField resignFirstResponder];
    [_localFareTextField resignFirstResponder];
    [_nationwideFareTextField resignFirstResponder];
}

#pragma mark - UIAlerView Delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        return;
    }
    
    if (alertView.tag == 1) {
        JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_PRODUCT_REMOVE];
        [request setValue:[_product valueForKey:@"id"] forParameter:@"productId"];
        NSDictionary* dict = [request synchronous];
        
        JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
        if (jmf.status == JMStatusSucceed) {
            
            [self.navigationController popViewControllerAnimated:true];
        }
        else {
            [Helper easyShowJMFStatus:jmf];
        }
    }
    
    else if (alertView.tag == 2 || alertView.tag == 3) {
        
        [self.navigationController popViewControllerAnimated:true];
    }
}

#pragma mark - FreightAreaSelectedDelegate

- (void)freightPicked:(NSDictionary *)freight;
{
    
    if (freight != nil) {
        [self renderFreightView:freight];
    }
}

@end
